import {Inject, Injectable} from "@nestjs/common";
import Redis from "ioredis";

@Injectable()
export class RedisService {
    constructor(
        @Inject("REDIS_CLIENT") private readonly redisClient: Redis
    ) {

    }

    /**
     * @Description: redis设置插入键值对
     * @author zhaojiuyi
     * @date 2023/4/15
     * @param {string} key 键
     * @param {string} value 值
     * @param {number} clearTime 设置过期时间
    */
    async setValue(key: string, value: any, clearTime?:number) {
        if (value instanceof Object){
            value = JSON.stringify(value)
        }
        await this.redisClient.set(key, value)
        if (clearTime) await this.redisClient.expire(key,clearTime)
    }

    /**
     * @Description: 根据kay获取value
     * @author zhaojiuyi
     * @date 2023/4/15
     * @param {string} key 键
     * @return {string | null}
     */
    async getValue<T=any>(key: string): Promise<T | string | null> {
        const result = await this.redisClient.get(key);
        try {
            return JSON.parse(result)
        }catch (e) {
            return result
        }
    }

    /**
     * @Description: 删除某个键
     * @author zhaojiuyi
     * @date 2023/4/15
     * @param {string} keys 键
     * @return {boolean}
    */
    delKay(...keys: string[]){
        this.redisClient.del(keys)
    }
}
